<template>
    <div class="addBrand-container">
      <div class="container">
        <el-form ref="ruleForm"
                 :model="ruleForm"
                 :rules="rules"
                 :inline="true"
                 label-width="180px"
                 class="demo-ruleForm">
          <div>
            <el-form-item label="学院名称:" prop="name">
              <el-input v-model="ruleForm.name"
                        placeholder="请填写学院名称"
                        maxlength="14" />
            </el-form-item>
          </div>
          
          <div>
            <el-form-item label="学院图片:" required prop="image">
              <image-upload :prop-image-url="imageUrl"
                            @imageChange="imageChange">
                图片大小不超过2M<br>仅能上传 PNG JPEG JPG类型图片<br>建议上传200*200或300*300尺寸的图片
              </image-upload>
            </el-form-item>
          </div>
          <div class="address">
            <el-form-item label="学院描述:">
              <el-input v-model="ruleForm.description"
                        type="textarea"
                        :rows="3"
                        maxlength="200"
                        placeholder="学院描述，最长200字" />
            </el-form-item>
          </div>
          <div class="subBox address">
            <el-form-item>
              <el-button @click="() => $router.back()">
                取消
              </el-button>
              <el-button type="primary"
                         :class="{ continue: actionType === 'add' }"
                         @click="submitForm('ruleForm', false)">
                保存
              </el-button>
              <el-button v-if="actionType === 'add'"
                         type="primary"
                         @click="submitForm('ruleForm', true)">
                保存并继续添加
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <el-dialog v-if="dialogVisible"
                 title="添加菜品"
                 class="addDishList"
                 :visible.sync="dialogVisible"
                 width="60%"
                 :before-close="handleClose">
        <AddDish v-if="dialogVisible"
                 ref="adddish"
                 :check-list="checkList"
                 :seach-key="seachKey"
                 :dish-list="dishList"
                 @checkList="getCheckList" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="addTableList">添 加</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts">
  import { Component, Vue } from 'vue-property-decorator'
  import HeadLable from '@/components/HeadLable/index.vue'
  import ImageUpload from '@/components/ImgUpload/index.vue' // 修正组件路径和命名
  import { addCollege, findCollegeById, updateCollege } from '@/api/college'
  import { baseUrl } from '@/config.json'
  import { FormInstance } from 'element-ui/types/form' // 导入表单类型
  // 定义数据接口
  interface CollegeForm {
    name: string
    image: string
    description: string
    id?: string
  }
  
  @Component({
    name: 'AddCollege',
    components: {
      HeadLable,
      ImageUpload
    }
  })
  export default class extends Vue {
    // 数据属性定义
    private value: string = ''
    private seachKey: string = ''
    private dishList: any[] = []
    private imageUrl: string = ''
    private actionType: string = 'add' // 统一使用actionType
    private dishTable: any[] = []
    private dialogVisible: boolean = false
    private checkList: any[] = []
    
    // 表单数据初始化
    private ruleForm: CollegeForm = {
      name: '',
      image: '',
      description: ''
    }
  
    // 表单验证规则
    get rules() {
      return {
        name: {
          required: true,
          validator: (rule: any, value: string, callback: Function) => {
            if (!value) {
              callback(new Error('请输入学院名称'))
            } else if (!/^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/.test(value)) {
              callback(new Error('学院名称需2-20个字符（汉字、字母、数字）'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        },
        image: {
          required: true,
          message: '学院图片不能为空',
          trigger: 'blur'
        }
      }
    }
  
    created() {
      // 初始化操作类型
      this.actionType = this.$route.query.id ? 'update' : 'add'
      if (this.actionType === 'update') {
        const id = this.$route.query.id as string
        if (id) {
          findCollegeById(Number(id))
            .then(res => {
              if (res.data.code === 1) {
                this.ruleForm = res.data.data
                this.imageUrl = this.ruleForm.image // 同步图片地址
              } else {
                this.$message.error(res.data.message)
                this.$router.push('/college')
              }
            })
            .catch(error => {
              console.error('获取学院信息失败:', error)
              this.$message.error('获取学院信息失败，请重试')
              this.$router.push('/college')
            })
        } else {
          this.$message.error('缺少学院ID')
          this.$router.push('/college')
        }
      }
    }
  
    // 搜索处理
    private seachHandle() {
      this.seachKey = this.value
    }
   // 声明表单引用类型
   $refs: {
    ruleForm: FormInstance;
  }
    // 表单提交处理（带类型注解）
    public submitForm(formName: string, isContinue: boolean): void {
      this.$refs[formName].validate((valid: boolean) => {
        if (valid) {
          // 表单校验通过，发送axios请求
          if (this.actionType === 'add') {
            addCollege(this.ruleForm)
              .then(res => {
                if (res.data.code === 1) {
                  this.$message.success('学院添加成功!')
                  if (isContinue) {
                    this.ruleForm = {
                      name: '',
                      image: '',
                      description: ''
                    }
                    this.imageUrl = ''
                  } else {
                    this.$router.push('/college')
                  }
                } else {
                  this.$message.error(res.data.message)
                }
              })
              .catch(error => {
                console.error('添加学院失败:', error)
                this.$message.error('添加学院失败，请重试')
              })
          } else {
            // 修改操作
            updateCollege(this.ruleForm)
              .then(res => {
                if (res.data.code === 1) {
                  this.$message.success('学院修改成功!')
                  this.$router.push('/college')
                } else {
                  this.$message.error(res.data.message)
                }
              })
              .catch(error => {
                console.error('更新学院失败:', error)
                this.$message.error('更新学院失败，请重试')
              })
          }
        }
      })
    }
  
    // 图片上传回调
    public imageChange(value: string): void {
      this.ruleForm.image = value
      this.imageUrl = value // 同步更新显示地址
    }
  
    // 对话框关闭处理
    private handleClose(): void {
      this.dialogVisible = false
    }
  
    // 添加菜品到表格
    private addTableList(): void {
      // 此处添加菜品处理逻辑
      this.dialogVisible = false
    }
  
    // 获取选中的菜品列表
    private getCheckList(list: any[]): void {
      this.checkList = list
    }
  }
  </script>
  
  <style>
  .avatar-uploader .el-icon-plus:after {
    position: absolute;
    display: inline-block;
    content: ' ' !important;
    left: calc(50% - 20px);
    top: calc(50% - 40px);
    width: 40px;
    height: 40px;
    background: url('./../../assets/icons/icon_upload@2x.png') center center no-repeat;
    background-size: 20px;
  }
  </style>
  
  <style lang="scss">
  .addBrand-container {
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  
    .avatar-uploader .el-upload:hover {
      border-color: #ffc200;
    }
  
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 200px;
      height: 160px;
      line-height: 160px;
      text-align: center;
    }
  
    .avatar {
      width: 200px;
      height: 160px;
      display: block;
    }
  
    .el-input {
      width: 293px;
    }
  
    .address {
      .el-form-item__content {
        width: 777px !important;
      }
    }
  
    .el-input__prefix {
      top: 2px;
    }
  
    .addDish {
      .el-input {
        width: 130px;
      }
  
      .el-input-number__increase {
        border-left: solid 1px #fbe396;
        background: #fffbf0;
      }
  
      .el-input-number__decrease {
        border-right: solid 1px #fbe396;
        background: #fffbf0;
      }
  
      input {
        border: 1px solid #fbe396;
      }
  
      .table {
        border: solid 1px #ebeef5;
        border-radius: 3px;
  
        th {
          padding: 5px 0;
        }
  
        td {
          padding: 7px 0;
        }
      }
    }
  
    .addDishList {
      .seachDish {
        position: absolute;
        top: 12px;
        right: 20px;
      }
  
      .el-dialog__footer {
        padding-top: 27px;
      }
  
      .el-dialog__body {
        padding: 0;
        border-bottom: solid 1px #efefef;
      }
  
      .seachDish {
        .el-input__inner {
          height: 40px;
          line-height: 40px;
        }
      }
    }
    }
  </style>
  
  <style lang="scss" scoped>
  .addBrand {
    &-container {
      margin: 30px;
  
      .container {
        position: relative;
        z-index: 1;
        background: #fff;
        padding: 30px;
        border-radius: 4px;
        min-height: 500px;
  
        .subBox {
          padding-top: 30px;
          text-align: center;
          border-top: solid 1px $gray-5;
        }
  
        .addDish {
          width: 777px;
  
          .addBut {
            background: #ffc200;
            display: inline-block;
            padding: 0px 20px;
            border-radius: 3px;
            line-height: 40px;
            cursor: pointer;
            border-radius: 4px;
            color: #333333;
            font-weight: 500;
          }
  
          .content {
            background: #fafafb;
            padding: 20px;
            border: solid 1px #d8dde3;
            border-radius: 3px;
          }
        }
      }
    }
  }
  </style>